package CanvaWeb.CanvaWeb.Service;

import CanvaWeb.CanvaWeb.Repository.GameStateRepository;
import CanvaWeb.CanvaWeb.Repository.RoomRepository;
import CanvaWeb.CanvaWeb.Repository.UserRepository;
import CanvaWeb.CanvaWeb.Repository.WordRepository;
import CanvaWeb.CanvaWeb.pojo.DrawingRequest;
import CanvaWeb.CanvaWeb.pojo.GameState;
import CanvaWeb.CanvaWeb.pojo.Room;
import CanvaWeb.CanvaWeb.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GameService {

    @Autowired
    private RoomRepository roomRepository;

    @Autowired
    private GameStateRepository gameStateRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private WordRepository wordRepository;

    public void nextTurn(Long roomId, String currentUsername) {
        // 获取当前游戏状态
        Room room = roomRepository.findById(roomId).orElseThrow(() -> new RuntimeException("Room not found"));
        GameState gameState = gameStateRepository.findByRoomId(roomId);

        // 获取当前用户和下一个用户
        User currentUser = gameState.getCurrentUser();
        User nextUser = gameState.getNextUser();  // 获取下一个用户

        // 如果没有下一个用户，说明游戏已结束
        if (nextUser == null) {
            // 游戏结束处理逻辑，比如显示总分
            return;
        }

        // 为下一个用户分配一个词语
        String wordToGuess = wordRepository.getRandomWord().getWord();
        gameState.setWordToGuess(wordToGuess);

        // 如果当前用户猜对了词语，更新得分
        if (guessCorrect(currentUser.getUsername(), wordToGuess)) {
            // 当前用户得分+1
            gameState.updateUserScore(currentUser, 1);
            currentUser.setScore(currentUser.getScore() + 1);  // 更新用户的得分
            userRepository.save(currentUser);  // 保存用户得分
        }

        // 更新游戏状态
        gameStateRepository.save(gameState);

        // 设置新的当前用户
        gameState.setCurrentUser(nextUser);  // 确保在下一轮由下一个用户开始
        gameStateRepository.save(gameState);
    }

    // 判断玩家是否猜对了词语
    private boolean guessCorrect(String userGuess, String wordToGuess) {
        return userGuess != null && userGuess.equalsIgnoreCase(wordToGuess);
    }
}



